package cc.vv.mvp.activity;

import android.os.Bundle;
import android.support.annotation.CallSuper;

import cc.vv.baselibrary.activity.BoTuBaseActivity;
import cc.vv.mvp.bean.BaseBinderBean;
import cc.vv.mvp.binder.BaseDataBinder;
import cc.vv.mvp.delegate.XDelegate;

/**
 * MVP模式的Activity基类
 * Created by sun.li on 2018/6/5.
 *
 * @author sun.li
 */

public abstract class BaseActivityMVP<T extends XDelegate> extends BoTuBaseActivity {

    /**
     * 视图托管类对象
     */
    protected T viewDelegate;

    /**
     * 公共数据视图绑定控制器对象
     */
    protected BaseDataBinder binder;

    public BaseActivityMVP() {
        try {
            viewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    @CallSuper
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        viewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        setContentView(viewDelegate.getRootView());
        initData();
        binder = getDataBinder();
        super.onCreate(savedInstanceState);
        viewDelegate.initWidget();
        bindEvenListener();
    }

    /**
     * 初始化界面数据
     */
    protected abstract void initData();

    /**
     * 注册界面控件点击事件
     */
    protected abstract void bindEvenListener();

    /**
     * 指定界面的视图控制器，必须指定
     */
    protected abstract Class<T> getDelegateClass();

    /**
     * 公共数据视图绑定控制器数据对象
     */
    public abstract BaseDataBinder getDataBinder();

    /**
     * 根据数据刷新视图
     */
    public <D extends BaseBinderBean> void notifyModelChanged(D data) {
        if (binder != null)
            binder.viewBindModel(viewDelegate, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /* 界面关闭解除视图绑定操作*/
        viewDelegate = null;
    }
}
